package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

/**
 * @Description TODO
 * @Author fantasy
 * @Date 2024/7/23 9:40
 **/


@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(csrf -> csrf.disable());
        http.authorizeHttpRequests(auth -> auth.requestMatchers("/admin/home").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().permitAll());
        http.formLogin(form -> form.loginPage("/login")
                .successHandler((request, response, authentication) -> {
                    System.out.println("登录成功");
                    response.sendRedirect("/admin/home");
                    request.getSession().setAttribute("loginUser", authentication.getName());
                }));
        http.logout(logout -> logout.logoutUrl("/logout")
                .logoutSuccessHandler((request, response, authentication) -> {
                    System.out.println("注销成功");
                    request.getSession().removeAttribute("loginUser");
                    response.sendRedirect("/login");
                }));
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {

        UserDetails admin = User.withUsername("admin").password("{noop}admin").roles("ADMIN","DEVELOPER").build();
        UserDetails user = User.withUsername("user").password("{noop}123456").roles("USER").build();

        return new InMemoryUserDetailsManager(admin,user);
    }
}
